package com.situ.springboot.controller;

import com.situ.springboot.constant.RedisConstants;
import com.situ.springboot.util.AliOSSUtil;
import com.situ.springboot.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
public class UploadController {

    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping("/upload")
    public Result upload(MultipartFile file) {
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String fileName = file.getOriginalFilename();
        String extension = fileName.substring(fileName.lastIndexOf("."));
        String newFileName = uuid + extension;
        //本地上传
        /*String filePath = "D:\\mypic\\" + newFileName;
        try {
            file.transferTo(new File(filePath));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }*/
        //阿里上传
        String url = "";
        try {
            url = AliOSSUtil.uploadFile(newFileName, file.getInputStream());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        //把上传的图片保存到redis
        redisTemplate.opsForSet().add(RedisConstants.UPLOAD_IMAGE, url);

        return Result.ok("上传成功", url);
    }
}
